CREATE OR REPLACE FUNCTION restart_sequences() RETURNS VOID AS '
DECLARE
  v_currval INTEGER;
BEGIN
  -- t_document
  SELECT COALESCE(MAX(doc_id) + 1, 1) INTO v_currval FROM t_document;
  EXECUTE ''ALTER SEQUENCE seq_document RESTART WITH '' || v_currval;
  
  -- t_corpus
  SELECT COALESCE(MAX(corp_id) + 1, 1) INTO v_currval FROM t_corpus;
  EXECUTE ''ALTER SEQUENCE seq_corpus RESTART WITH '' || v_currval;
  
  -- t_lang_resource
  SELECT COALESCE(MAX(lr_id) + 1, 1) INTO v_currval FROM t_lang_resource;
  EXECUTE ''ALTER SEQUENCE seq_lang_resource RESTART WITH '' || v_currval;

  -- t_doc_encoding
  SELECT COALESCE(MAX(enc_id) + 1, 1) INTO v_currval FROM t_doc_encoding;
  EXECUTE ''ALTER SEQUENCE seq_doc_encoding RESTART WITH '' || v_currval;

  -- t_document_corpus
  SELECT COALESCE(MAX(cd_id) + 1, 1) INTO v_currval FROM t_corpus_document;
  EXECUTE ''ALTER SEQUENCE seq_corpus_document RESTART WITH '' || v_currval;

  -- t_doc_content
  SELECT COALESCE(MAX(dc_id) + 1, 1) INTO v_currval FROM t_doc_content;
  EXECUTE ''ALTER SEQUENCE seq_doc_content RESTART WITH '' || v_currval;
  
  -- t_feature
  SELECT COALESCE(MAX(ft_id) + 1, 1) INTO v_currval FROM t_feature;
  EXECUTE ''ALTER SEQUENCE seq_feature RESTART WITH '' || v_currval;

  -- t_feature_key
  SELECT COALESCE(MAX(fk_id) + 1, 1) INTO v_currval FROM t_feature_key;
  EXECUTE ''ALTER SEQUENCE seq_feature_key RESTART WITH '' || v_currval;

  -- t_doc_encoding
  SELECT COALESCE(MAX(enc_id) + 1, 1) INTO v_currval FROM t_doc_encoding;
  EXECUTE ''ALTER SEQUENCE seq_doc_encoding RESTART WITH '' || v_currval;

  -- t_user
  SELECT COALESCE(MAX(usr_id) + 1, 1) INTO v_currval FROM t_user;
  EXECUTE ''ALTER SEQUENCE seq_user RESTART WITH '' || v_currval;

  -- t_user_group
  SELECT COALESCE(MAX(ugrp_id) + 1, 1) INTO v_currval FROM t_user_group;
  EXECUTE ''ALTER SEQUENCE seq_user_group RESTART WITH '' || v_currval;

END;
' LANGUAGE 'plpgsql';

-- SELECT restart_sequences();